package main

import "fmt"

func main() {
	nums := []int{2, 3, 4, 5, 6, 1, 8}
	sortNums := sort(nums)
	for _, v := range sortNums {
		fmt.Println(v)
	}
}

//鸡尾酒排序,适合待排序的数字中，大量元素已经有序的情况
func sort(nums []int) []int {
	numsLen := len(nums)
	round := numsLen / 2
	for i := 0; i < round; i++ {
		//奇数轮次，从左到右排序
		isSorted := true
		for j := i; j < numsLen-i-1; j++ {
			if nums[j] > nums[j+1] {
				nums[j], nums[j+1] = nums[j+1], nums[j]
				isSorted = false
			}
		}
		if isSorted {
			break
		}

		//偶数轮次，从右到左排序
		isSorted = true
		for j := numsLen - i - 1; j > i; j-- {
			if nums[j] < nums[j-1] {
				nums[j], nums[j-1] = nums[j-1], nums[j]
				isSorted = false
			}
		}

		if isSorted {
			break
		}
	}

	return nums
}
